<template>
    <div>
        <ul>
            <li v-for="user of users" :key="user.id">{{user.name}}</li>
        </ul>
    </div>
    <router-link :to="{name:'user',query:{id:Math.random()}}">下一页</router-link>
    <!-- <button @click="page = 2">第2页--{{page}}</button> -->
</template>

<script setup>
    import {watch,ref} from "vue"
    import {useRoute,onBeforeRouteUpdate,onBeforeRouteLeave} from 'vue-router'
    let users = ref([]);
    const route = useRoute();
    // users.value = await fetch(`http://127.0.0.1:3005/users`).then(r => r.json());
    // onBeforeRouteUpdate(async() => {
    //     users.value = await fetch(`http://127.0.0.1:3005/users`).then(r => r.json());
    // });

    // 使用watch监听路由
    watch(route,async route => {
        if(route.name == 'user'){
            users.value = await fetch(`http://127.0.0.1:3005/users`).then(r => r.json());
        }
    },{immediate:true});

    // 使用watch根据page监听路由
    // const page = ref(route.query.page ?? 1);
    // watch(page,async page => {
    //     users.value = await fetch(`http://127.0.0.1:3005/users?page=${page}`).then(r => r.json());
    // },{immediate:true})

</script>

<style lang="scss" scoped>
    a{
    display: inline-block;
    background-color:#e67e22;
    color: #fff;
    padding:20px;
  }
</style>